package thread.synchronize;

/**
 * @author 真香
 * @create 2021-06-04 16:12
 */


/**
 * 不安全的买票
 *
 *  1、线程不安全，同时拿到第2张票，票数有负数
 *
 */
public class UnsafeBuyTicket {


    public static void main(String[] args){
        BuyTicket ticket = new BuyTicket();

        new Thread(ticket,"小明").start();
        new Thread(ticket,"小张").start();
        new Thread(ticket,"黄牛党").start();

    }
}



class BuyTicket implements Runnable {


    // 票
    private int ticketNum = 10;

    private boolean flag = true;


    @Override
    public void run() {
    // 买票
        while (flag) {

            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private synchronized void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        // 模拟延时
        Thread.sleep(1000);

        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNum--+"票");
    }



}
